import { Request, Response } from "express";
import * as UserService from "../services/user.service";
import { ResponseUtil } from "../utils/response.util";
import jwt from "jsonwebtoken";
// 获取所有用户
export const getAllUsers = async (req: Request, res: Response) => {
  try {
    const page = Number(req.query.page);
    const pageSize = Number(req.query.pageSize);
    const options = req.body;
    const users = await UserService.getAllUsers(page, pageSize, options);
    ResponseUtil.success(res, users, "查询用户成功");
  } catch (err) {
    ResponseUtil.error(res, err, "查询用户失败");
  }
};

// 根据ID获取用户
export const getUserById = async (req: Request, res: Response) => {
  try {
    const id = Number(req.params.id);
    const user = await UserService.getUserById(id);
    if (!user) return ResponseUtil.success(res, user, "用户不存在");
    ResponseUtil.success(res, user, "查询用户成功");
  } catch (err) {
    ResponseUtil.error(res, err, "获取用户失败");
  }
};

// 创建用户
export const createUser = async (req: Request, res: Response) => {
  try {
    console.log(req.body);
    const user = await UserService.createUser(req.body);
    ResponseUtil.success(res, user, "创建用户成功");
  } catch (err) {
    ResponseUtil.error(res, err, "创建用户失败");
  }
};

// 更新用户
export const updateUser = async (req: Request, res: Response) => {
  try {
    const id = Number(req.params.id);
    const user = await UserService.updateUser(id, req.body);
    ResponseUtil.success(res, user, "更新用户成功");
  } catch (err) {
    ResponseUtil.error(res, err, "更新用户失败");
  }
};

// 删除用户
export const deleteUser = async (req: Request, res: Response) => {
  try {
    const id = Number(req.params.id);
    const deleteOne = await UserService.deleteUser(id);
    ResponseUtil.success(res, deleteOne, "删除成功");
  } catch (err) {
    ResponseUtil.error(res, err, "删除用户失败");
  }
};

// 登录验证
export const login = async (req: Request, res: Response) => {
  try {
    const { username, password } = req.body;
    const user = await UserService.verifyLogin(username, password);
    if (!user) return ResponseUtil.error(res, null, "用户或密码错误");
    // 返回token
    const token = jwt.sign(
      {
        id: user.id,
        username: user.username,
      },
      process.env.JWT_SECRET!,
      {
        expiresIn: "8h",
      }
    );
    ResponseUtil.success(res, { token, user }, "登录成功");
  } catch (err) {
    ResponseUtil.error(res, err, "登录失败");
  }
};
